package com.qingchunlin.blogsystem.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtils {
    //过期时间30min
    private final static long expiration = 30 * 60 * 1000;
    //自定义秘钥
    private static final String secretString = "puxgvEEwz8nU4U1TA9W5/3jwkJdBuTlgRsrbz8gaNpw=";
    //生成签名秘钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String createJWTToken(Map<String, Object> claims) {
        //现在系统时间
        Date now = new Date(System.currentTimeMillis());

        String token = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(new Date(now.getTime() + expiration))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();

        return token;
    }

    public static Claims parseJWTToken(String token) {
        if (token == null) {
            return null;
        }

        JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = jwtParser.parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("解析token失败, token: token{}", token);
        }

        return claims;
    }

    public static Integer getUserIdByToken(String token) {
        Claims claims = parseJWTToken(token);
        if (claims == null) {
            return null;
        }
        return (Integer) claims.get("id");
    }

}
